#include <avkon.hrh>
#include <barsread.h>
#include <akntitle.h>
#include <aknnavi.h>
#include <akncontext.h>
#include <AknsUtils.h>
#include <s32file.h>
#include <AknGlobalNote.h> 
#include <aknmessagequerydialog.h>
#include <apgwgnam.h>
#include <hlplch.h>
#include <centralrepository.h>
#include <e32property.h>
#include <hwrmvibra.h>
#include <APGCLI.H>
#include <MrLockUi.rsg>
#include <SysUtil.h>
#include <HWRMLight.h>
#include <Hal.h>

#include "AppUi.h"
#include "MrLock.hrh"
#include "Logger.h"
#include "SettingsListBox.h"
#include "Application.h"
#include "Utils.h"
#include "AutoLockView.h"

CHelpNotes::CHelpNotes()
{
}

CHelpNotes::~CHelpNotes()
{
	iDontShowNotes.Close();
}

void CHelpNotes::ConstructL()
{
	TRAPD( unused, LoadArrayL() );
}

void CHelpNotes::ShowHelpNoteL( THelpNoteId aNoteId )
{
	if( iDontShowNotes.Find( aNoteId ) != KErrNotFound )
		return;

	TInt textResId = 0;
	switch( aNoteId )
	{
	case EMrLockDisabled:
		textResId = R_TEXT_MRLOCK_DISABLED;
		break;
	case EMrLockEnabled:
		textResId = R_TEXT_MRLOCK_ENABLED;
		break;
	}

	if( textResId != 0 )
	{
		CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL( Utils::GetR( textResId ) );
		dlg->PrepareLC( R_HELP_MESSAGE_DIALOG );
		TInt res = dlg->RunLD();
		if( res == EFalse )
		{
			iDontShowNotes.Append( aNoteId );
			TRAPD( err, SaveArrayL() );
		}
	}
}

void CHelpNotes::SaveArrayL()
{
	DefAppUi;
	if( !appUi->EnoughSpace( EFalse ) )
		return;

	CDictionaryStore* iniFile = CDictionaryFileStore::OpenLC( CEikonEnv::Static()->FsSession() , KSettingsFileName, KUidMyApp);
	Utils::SaveIntArrayL( iniFile, ESettingIdDontShowNotes, iDontShowNotes.Array() );
	CleanupStack::PopAndDestroy();
}

void CHelpNotes::LoadArrayL()
{
	CDictionaryStore* iniFile = CDictionaryFileStore::OpenLC( CEikonEnv::Static()->FsSession() , KSettingsFileName, KUidMyApp);
	Utils::LoadIntArrayL( iniFile, ESettingIdDontShowNotes, iDontShowNotes );
	CleanupStack::PopAndDestroy();
}

CAppUi::CAppUi()
{
}

void CAppUi::ShowPrivacyDialogL()
{	
	HBufC* text = CEikonEnv::Static()->AllocReadResourceLC(R_TEXT_PRIVACY_BODY);
	CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL(*text);
	dlg->PrepareLC(R_ABOUT_DIALOG);
	dlg->Heading()->SetTextL(GetR(R_TEXT_PRIVACY_HEADING));
	TInt res = dlg->RunLD();
	CleanupStack::PopAndDestroy();//-text
}

void CAppUi::ConstructL()
{
	BaseConstructL(EAknEnableSkin);

	RFs& fs = CEikonEnv::Static()->FsSession();
	fs.SetSessionPath(Application()->AppFullName().Left(2));

	iGlobalNote = CAknGlobalNote::NewL();

	iObserver.Connect();

	iHelpNotes = new( ELeave ) CHelpNotes();
	iHelpNotes->ConstructL();

	iAutolockView = CAutolockView::NewL();
	AddViewL(iAutolockView);

	SetDefaultViewL(*iAutolockView);
}

CAppUi::~CAppUi()
{
	delete iGlobalNote;
	HideTabsL();
	iObserver.Close();
	delete iHelpNotes;
}

TKeyResponse CAppUi::HandleKeyEventL(const TKeyEvent& aKeyEvent, TEventCode /*aType*/)
{
	return EKeyWasNotConsumed;
	TInt code = aKeyEvent.iCode;

	CAknTabGroup* tabGroup = NULL;
	if (code == EKeyLeftArrow || code == EKeyRightArrow)
	{
		CAknNavigationControlContainer* np = (CAknNavigationControlContainer*) StatusPane()->ControlL(TUid::Uid(EEikStatusPaneUidNavi));
		tabGroup = static_cast<CAknTabGroup*>(np->Top()->DecoratedControl());
	}

    switch (code)
    {
        case EKeyLeftArrow:
        {//go to the Keypad view
        	TInt newIndex = tabGroup->ActiveTabIndex()-1;
            if (newIndex >= 0)
			{
				tabGroup->SetActiveTabByIndex(newIndex);
				ActivateLocalViewL(TUid::Uid(tabGroup->ActiveTabId()));
				return EKeyWasConsumed;
            }
			break;
		}
        case EKeyRightArrow:
        {//go to LockPhoneView
			TInt newIndex = tabGroup->ActiveTabIndex()+1;
			if (newIndex < tabGroup->TabCount())
			{
				tabGroup->SetActiveTabByIndex(newIndex);
				ActivateLocalViewL(TUid::Uid(tabGroup->ActiveTabId()));
				return EKeyWasConsumed;
			}
			break; 
        }
        default:
        	break;
	}
	return EKeyWasNotConsumed;
}

void CAppUi::HandleCommandL( TInt aCommand )
{
	switch ( aCommand )
	{
		case EEikCmdExit:
		case EAknSoftkeyExit:
		{
			Exit();
			break;
		}
		case EHelpCmd:
		{
			CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
			HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
			break;
		}
		case EAknSoftkeyBack:
		{
			HideTabsL();
			ActivateLocalViewL(TUid::Uid(EMainViewId));
			break;
		}
		case EPrivacyCmd:
		{
			ShowPrivacyDialogL();
			break;
		}
		case EAboutCmd:
		{
			CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog();
			dlg->PrepareLC(R_ABOUT_DIALOG);
			TBuf<300> text;
			text.Copy(_L("Mr Lock 1.11"));
			text.Append(GetR(R_TEXT_ABOUT_BODY));

			dlg->SetMessageText(text);
			TCallBack callback(StartLinkL, this);
			dlg->SetLink(callback);
			dlg->RunLD();
			break;
		}
		default:
			break;
	}
}

TDes& CAppUi::GetR(TInt aResId)
{	
	CCoeEnv::Static()->ReadResourceL(iTempText, aResId);	
	return iTempText;
}

void CAppUi::StartUrlL(const TDesC& aUrl)
{
	HBufC* param = HBufC::NewLC(256);
	param->Des().Format( _L( "4 %S" ), &aUrl);

	// Wap Browser's constants UId
	const TInt KWmlBrowserUid = 0x10008D39;
	TUid id(TUid::Uid( KWmlBrowserUid));

	TApaTaskList taskList( CEikonEnv::Static()->WsSession() );
	TApaTask task = taskList.FindApp( id );
	if ( task.Exists() )
	{
		HBufC8* param8 = HBufC8::NewLC( param->Length() );
		param8->Des().Append( *param );
		task.SendMessage( TUid::Uid( 0 ), *param8 ); // Uid is not used
		CleanupStack::PopAndDestroy(); // param8
	}
	else
	{
		RApaLsSession appArcSession;
		User::LeaveIfError(appArcSession.Connect()); // connect to AppArc server
		TThreadId id;
		appArcSession.StartDocument( *param, TUid::Uid( KWmlBrowserUid ), id );
		appArcSession.Close();
	}
	CleanupStack::PopAndDestroy(); // param
}

TInt CAppUi::StartLinkL(TAny* aObj)
{
	CAppUi* obj = (CAppUi*) aObj;
	obj->StartUrlL(_L("www.mobifunsoft.com/mrlock"));
	return 1;
}

void CAppUi::ShowTabsL(TInt aStartInd)
{
	HideTabsL();
	TResourceReader reader;
	iCoeEnv->CreateResourceReaderLC(reader, R_NAVI_DECORATOR);//+reader
	CAknNavigationControlContainer* np = (CAknNavigationControlContainer*) StatusPane()->ControlL(TUid::Uid(EEikStatusPaneUidNavi));
	iNaviTabs = np->CreateTabGroupL(reader);
	CleanupStack::PopAndDestroy();//-reader
	CAknTabGroup* tabGroup =static_cast<CAknTabGroup*>(iNaviTabs->DecoratedControl());
	tabGroup->SetActiveTabByIndex(aStartInd);
	np->PushL(*iNaviTabs);
}

void CAppUi::HideTabsL()
{
	if (iNaviTabs)
	{
		CAknNavigationControlContainer* np = (CAknNavigationControlContainer*) StatusPane()->ControlL(TUid::Uid(EEikStatusPaneUidNavi));
		np->Pop();
		delete iNaviTabs;
		iNaviTabs = NULL;
	}
}

void CAppUi::ShowMessageL(const TDesC& aText, TAknGlobalNoteType aType)
{
	iGlobalNote->ShowNoteL(aType, aText);
}


void CAppUi::HandleResourceChangeL(TInt aType)
{
	CAknAppUi::HandleResourceChangeL(aType);
	if  (aType == KEikDynamicLayoutVariantSwitch)
	{//do re-layout
		if (iAutolockView->iListBox)
			iAutolockView->iListBox->SetRect(iAutolockView->ClientRect());
	}
}

void CAppUi::HandleForegroundEventL(TBool aForeground)
{
	CAknAppUi::HandleForegroundEventL(aForeground);
}

void CAppUi::ShowErrorNoteL(TInt aResId)
{
	iErrorNote = new (ELeave) CAknErrorNote(ETrue);
	iErrorNote->ExecuteLD(GetR(aResId));
}

TBool CAppUi::EnoughSpace(TBool aShowNote)
{
	if (SysUtil::FFSSpaceBelowCriticalLevelL(&CEikonEnv::Static()->FsSession(), 1000))
	{
		if (aShowNote)
			ShowErrorNoteL(R_TEXT_NOT_ENOUGH_SPACE);
		return EFalse;
	}
	return ETrue;
}

void CAppUi::ShowHelpNoteL( CHelpNotes::THelpNoteId aNoteId )
{
	iHelpNotes->ShowHelpNoteL( aNoteId );
}
